using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using sand_game_core;
using System.Threading;
using System.IO;

namespace sand_game
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class pc_game : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D screen;
        bool updated;
        Color clearColor;
        Rectangle clearRect;
        Player p;
        RenderTarget2D screenshot;
        int screenshotimage;
        FileStream fs;
        int gamePhase;
        public pc_game()
        {
            gamePhase = 0;
            bitmapWriter.init(800, 480);
            Window.AllowUserResizing = true;
            screenshotimage = 0;
            Thread.CurrentThread.Priority = ThreadPriority.Normal;
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "sand game content";
            clearColor = new Color(0, 0, 0, 0.1f);
            clearRect = new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height);
            Window.ClientSizeChanged += new EventHandler<EventArgs>(Window_ClientSizeChanged);
        }

        void Window_ClientSizeChanged(object sender, EventArgs e)
        {
            bitmapWriter.init(Window.ClientBounds.Width, Window.ClientBounds.Height);
            world.width = (uint)Window.ClientBounds.Width;
            world.height = (uint)Window.ClientBounds.Height;
            world.rect = new Rectangle(0, 0, (int)Window.ClientBounds.Width, Window.ClientBounds.Height);
        }
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            sand_game_core.random.rnd = new Random();
            world.initialize(Window.ClientBounds, GraphicsDevice);
            sand_game_core.view.initialize();
            base.Initialize();
            graphics.SynchronizeWithVerticalRetrace = false;
            p = new Player(Content);

        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here

        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (!updated)
            {
                updated = true;

                // Allows the game to exit
                if (Keyboard.GetState()[Keys.Escape] == KeyState.Down)
                    this.Exit();
                /*if (Keyboard.GetState()[Keys.PageDown] == KeyState.Down)
                    sand_game_core.view.zoomIn();
                if (Keyboard.GetState()[Keys.PageUp] == KeyState.Down)
                    sand_game_core.view.zoomOut();
                if (Keyboard.GetState()[Keys.P] == KeyState.Down)
                    world.worldStop();
                if (Keyboard.GetState()[Keys.O] == KeyState.Down)
                    world.worldstart();*/
                p.update(Window.ClientBounds.Height);
                view.Update(p.position.X - Window.ClientBounds.Width / (int)view.multiply / 2, p.position.Y - Window.ClientBounds.Height / (int)view.multiply / 2);
                Window.Title = "x: " + sand_game_core.view.x + ", Y: " + sand_game_core.view.y + ", frame: " + p.frameNo;
                // TODO: Add your update logic here
            }
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {

            using (screenshot = new RenderTarget2D(GraphicsDevice, Window.ClientBounds.Width, Window.ClientBounds.Height, false, SurfaceFormat.Color, DepthFormat.None))
            {
                GraphicsDevice.SetRenderTarget(screenshot);
                GraphicsDevice.Clear(clearColor);
                spriteBatch.Begin();
                p.draw(spriteBatch);
                world.draw(spriteBatch);
                spriteBatch.End();
                GraphicsDevice.SetRenderTarget(null);
                //bitmapWriter.TextureToBmp(screenshot, "screenshots/screenshot" + (screenshotimage >= 1000 ? "" : screenshotimage >= 100 ? "0" : screenshotimage >= 10 ? "00" : "000") + (screenshotimage++) + ".jpg");
                GraphicsDevice.Clear(clearColor);
                spriteBatch.Begin();
                spriteBatch.Draw(screenshot, new Rectangle(0, 0, Window.ClientBounds.Width, Window.ClientBounds.Height), Color.White);
                spriteBatch.End();
                updated = false;
            }
            base.Draw(gameTime);
        }
    }
}
